﻿using System;
using System.Collections.Generic;
using Repetition.Persistence;
using Repetition.Domain;

namespace Repetition.Persistence.FluentNHibernate
{
    public class PersistentSubjectList : ISubjectList
    {
        private IList<Subject> subjects = new List<Subject>();
        private ISubjectRepository repository;

        public PersistentSubjectList()
            : this(new List<Subject>()) { }

        public PersistentSubjectList(ICollection<Subject> subjects)
            : this(subjects, new SubjectRepository()){ }

        public PersistentSubjectList(ISubjectRepository repository)
            : this(new List<Subject>(), repository) { }

        public PersistentSubjectList(ICollection<Subject> subjects, ISubjectRepository repository)
        {
            AddCollection(subjects);
            this.repository = repository;
        }

        public void Add(Subject subject)
        {
            repository.Add(subject);
            subjects.Add(subject);
        }

        public void SaveChanges(Subject subject)
        {
            repository.Update(subject);
        }

        public void Remove(Subject subject)
        {
            bool wasRemovedFromList = subjects.Remove(subject);

            if (wasRemovedFromList)
                repository.RemoveSubjectAndOrphanProblems(subject);
        }

        public void Load()
        {
            subjects.Clear();
            var collection = repository.GetAll();
            AddCollection(collection);
        }

        public int Count
        {
            get { return subjects.Count; }
        }

        public ICollection<Subject> GetAll()
        {
            return subjects;
        }

        public void Dispose()
        {
            repository.Dispose();
        }

        public void Clear()
        {
            subjects.Clear();
        }

        private void AddCollection(ICollection<Subject> subjects)
        {
            foreach (var subject in subjects)
                this.subjects.Add(subject);
        }
    }
}